<template>
  <a-card>
    <span slot="title">
      <label class="back-title" @click="goRoleList"><a-icon type="left" /> {{ role.name }} - 用户分配</label>
    </span>
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48"> </a-row>
      </a-form>
    </div>
    <div style="margin-bottom: 16px">
      <a-row>
        <a-col :span="3">
          <dept-user-tree :type="'user'" :multiple="true" @change="userChange" :input="false" @save="saveHandle" />
        </a-col>
        <a-col :span="21">
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm
                  :title="'已选择' + selectedRowKeys.length + '项,确定删除吗？'"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delHa_role_users"
                >
                  <a-icon type="delete" />&nbsp;删除
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
            <a-button v-show="selectedRowKeys.length > 0" style="margin-left: 8px">
              批量操作 <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </a-col>
      </a-row>
    </div>
    <div class="spin-content">
      已选择&nbsp;
      <a style="font-weight: 600" v-text="selectedRowKeys.length"></a>
      项&nbsp;
      <a style="margin-left: 24px" @click="() => (selectedRowKeys = [])">清空</a>
    </div>
    <a-table
      :scroll="{ x: 1500, y: 500 }"
      :columns="ucolumns"
      :data-source="udata"
      :pagination="upagination"
      :loading="loading"
      rowKey="id"
      @change="tableChange"
      size="middle"
      :bordered="ubordered"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
      </span>
      <span slot="operation" slot-scope="text, record">
        <template>
          <a-popconfirm title="确定删除吗？" ok-text="确定" cancel-text="取消" @confirm="delHa_role_userById(record)">
            <a-icon slot="icon" type="delete" />
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>
    <!-- <a-modal title="选择用户" :visible="visible" :bodyStyle="{ height: '50vh' }" @cancel="visible = false" width="30%">
      <template slot="footer">
        <a-button key="back" @click="visible = false"> 取消 </a-button>
        <a-button key="submit" type="primary" :loading="confirmLoading" @click="saveHandle"> 保存 </a-button>
      </template>
      <a-row>
        <a-col :span="24" style="height: 45vh; overflow: auto">
          <dept-user-tree :type="'user'" :checkable="true" @change="userChange" :input="false" @save="saveHandle"/>
        </a-col>
      </a-row>
    </a-modal> -->
  </a-card>
</template>

<style lang="css" scope src="@/style/css/style.css"></style>

<script>
import { delHa_role_users, delHa_role_user, queryHa_role_userList, output, batchSave } from '@/api/base/ha_role_user'
import { viewHa_role } from '@/api/base/ha_role'
import deptUserTree from '@/views/base/DeptUserTree'

export default {
  data() {
    return {
      role: { name: '' },
      visible: false,
      confirmLoading: false,
      loading: false, // 遮罩是否显示
      ubordered: false, // 表格边框是否显示
      queryParam: {
        pageNumber: 1,
        pageSize: 20
      }, // 查询条件
      selectedRowKeys: [], // 选中的行id
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      ucolumns: [
        {
          title: '姓名',
          dataIndex: 'name',
          width: '15%',
          sorter: (a, b) => a.name.localeCompare(b.name),
          align: 'left'
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          width: '1',
          sorter: (a, b) => a.moble.localeCompare(b.moble),
          align: 'left'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '80px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ], // 表头
      selectedUsers: [],
      pageNumber: null, // 角色列表的页码
      f_name: null // 角色列表的查询条件
    }
  },
  created() {
    let roleid = this.$route.query.id
    this.pageNumber = this.$route.params.pageNumber
    this.f_name = this.$route.params.f_name
    viewHa_role(roleid).then(res => {
      if (res.code === 0) {
        this.role = res.data
        this.findHa_role_userList(this.queryParam)
      }
    })
  },
  methods: {
    // 跳转回角色列表
    goRoleList() {
      this.$router.push({ name: 'ha_role', query: { pageNumber: this.pageNumber, f_name: this.f_name } })
    },
    /**
     *  查询角色用户列表
     */
    findHa_role_userList(queryParam) {
      queryParam.f_roleid = this.role.id
      this.loading = true
      const a = Date.now()
      queryHa_role_userList(queryParam).then(res => {
        this.udata = res.data.records
        // 将当前页码和数量与后台绑定
        this.upagination.total = res.data.total
        this.upagination.current = res.data.current
        this.upagination.pageSize = res.data.size
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {}
      this.findHa_role_userList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findHa_role_userList(this.queryParam)
    },
    /**
     * 查询
     */
    searchHa_role_user() {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      // this.upagination.current = 1
      this.findHa_role_userList(this.queryParam)
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 打开抽屉
     */
    showDrawer() {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose() {
      this.visible = false
    },
    /**
     * 进入新增页面
     */
    handleAdd() {
      this.visible = true
    },
    /**
     * 进入编辑页面
     */
    handleEdit(res, isView) {
      this.isView = isView
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findHa_role_userById(res.id, isView)
      }, 10)
    },
    /**
     * 删除角色用户
     */
    delHa_role_userById(res) {
      delHa_role_user(res.id).then(res => {
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.findHa_role_userList(this.queryParam)
          this.$message.success('删除成功')
        }
      })
    },
    /**
     * 批量删除角色用户
     */
    delHa_role_users() {
      delHa_role_users({ ids: this.selectedRowKeys.toString() }).then(res => {
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.findHa_role_userList(this.queryParam)
          this.$message.success('删除成功')
        }
      })
    },
    /**
     *  导出Excel
     */
    exportExcel() {
      output()
        .then(response => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '角色用户.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function() {
          console.log(error)
        })
    },
    userChange(selectedNodes) {
      this.selectedUsers = []
      selectedNodes.forEach(item => {
        this.selectedUsers.push({ roleid: this.role.id, userid: item.id.substr(item.id.indexOf('_') + 1) })
      })
    },
    saveHandle() {
      if (this.selectedUsers.length === 0) {
        this.$message.error('请选择用户')
        return
      }
      let params = { roleId: this.role.id }
      batchSave(params, this.selectedUsers).then(res => {
        if (res.code === 0) {
          this.$message.success('保存成功')
          this.visible = false
          this.findHa_role_userList(this.queryParam)
        }
      })
    }
  },
  components: {
    'dept-user-tree': deptUserTree
  }
}
</script>
